#! /usr/bin/env bash

#  Licensed to the Apache Software Foundation (ASF) under one
#  or more contributor license agreements.  See the NOTICE file
#  distributed with this work for additional information
#  regarding copyright ownership.  The ASF licenses this file
#  to you under the Apache License, Version 2.0 (the
#  "License"); you may not use this file except in compliance
#  with the License.  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

TSQA_TSXS=${TSQA_TSXS:-/opt/ats/bin/tsxs}
TSQA_TESTNAME=$(basename $0)
source $(dirname $0)/functions

# The intercept example plugin is hard-coded to port 60000.
SERVER_PORT=${SERVER_PORT:-60000}

# Use traffic_line -m to list all the configuration variables. Verify their values with
# traffic_line -r. This tests the TSRecordGet() and TSRecordGetMatchMult() remote APIs.
check() {
  local key
  local val1
  local val2

  local bindir=$(bindir)

  tsexec traffic_line -m proxy.config | while read key val1 ; do
    val2=$(TS_ROOT=$TSQA_ROOT $bindir/traffic_line -r $key)
    if [ "$?" != "0" ]; then
      fail failed to fetch value for $key
    elif [ "$val1" != "$val1" ] ; then
      fail value mismatch for $key, expected:\"$val1\", received:\"$val2\"
    fi
  done
}

bootstrap

if [ ! -x $(bindir)/jtest ] ; then
  fatal "missing jtest program; rebuild with --enable-test-tools"
fi

cat >$TSQA_ROOT/$(sysconfdir)/remap.config <<REMAP
map http://jtest.trafficserver.apache.org:$SERVER_PORT http://127.0.0.1:$SERVER_PORT
REMAP

cat >$TSQA_ROOT/$(sysconfdir)/plugin.config <<REMAP
#intercept.so
REMAP

# If Traffic Server is not up, bring it up ...
alive cop || startup || fatal unable to start Traffic Server
trap shutdown 0 EXIT

# Wait for traffic_manager to start.
alive manager
alive server
msgwait 1

# Run jtest for a while to exercise the intercept path. Note that jtest only exercises
# one of many possible sequences of events. Specifically, the jtest server will always
# close the socket before the client finishes reasing the response.
$(bindir)/jtest --proxy_port $PORT --proxy_host 127.0.0.1 \
  --server_port $SERVER_PORT --server_host jtest.trafficserver.apache.org \
  --clients 10 --test_time 60

# Check for a crash ...
crash

exit $TSQA_FAIL

# vim: set sw=2 ts=2 et :
